package com.citycloud.ccuap.tc.admin.projectapp;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.SelectProvider;

import com.citycloud.ccuap.commons.db.SqlRestrictions;
import com.citycloud.ccuap.framework.mybatis.pagination.Pagination;

@Mapper
public interface SysAppMapper {
    @SelectProvider(
            type = SysAppMapper.RepositoryProvider.class,
            method = "querySysAppPage"
    )
    List<Map<String, Object>> querySysAppPage(Pagination var1, Map<String, Object> var2);

    @SelectProvider(
            type = SysAppMapper.RepositoryProvider.class,
            method = "querySysApps"
    )
    List<Map<String, Object>> querySysApps(Integer appType, Long projectId);

    public static class RepositoryProvider {
        public RepositoryProvider() {
        }

        public String querySysAppPage(Map<String, Object> param) {
            String sql = " SELECT sa.app_name AS appName,sa.client_id AS clientId,oc_d.resource_ids AS resource,oc_d.authorized_grant_types AS authorizedGrantTypes,GROUP_CONCAT(sp.project_id) AS projectIds FROM sys_app AS sa LEFT JOIN sys_project AS sp ON sa.client_id = sp.client_id LEFT JOIN oauth_client_details AS oc_d ON oc_d.client_id = sa.client_id WHERE 1 = 1 ";
            if (param != null && Objects.nonNull(param.get("appType"))) {
                sql = sql + SqlRestrictions.eq("sa.app_type", param.get("appType"));
            }
            sql = sql + " group by sa.client_id " + SqlRestrictions.order("sa.app_id", 1);
            return sql;
        }

        public String querySysApps(Integer appType, Long projectId) {
            StringBuilder sql = new StringBuilder();
            sql.append("select app.app_name as appName, app.client_id as clientId from sys_app app ");
            sql.append("where 1=1 ");
            if (projectId != null) {
                sql.append(" and not EXISTS ( select pr.client_id  from sys_project pr where  app.client_id = pr.client_id ");
                sql.append(SqlRestrictions.ne("pr.project_id ", projectId));
                sql.append(" )");
            }else{
                sql.append(" and not EXISTS ( select pr.client_id  from sys_project pr where  app.client_id = pr.client_id )");
            }
            
            if (appType != null) {
                sql.append(SqlRestrictions.eq("app.app_type", appType));
            }
            return sql.toString();
        }
    }
}
